<template>
  <div class="behavior-definition-panel">
    <!-- 工具栏 -->
    <div class="toolbar">
      <a-space>
        <a-button type="primary" @click="showCreateModal">
          <template #icon>
            <IconifyIcon icon="ant-design:plus-outlined" />
          </template>
          新建行为定义
        </a-button>
        <a-button @click="refreshData">
          <template #icon>
            <IconifyIcon icon="ant-design:reload-outlined" />
          </template>
          刷新
        </a-button>
      </a-space>

      <a-space>
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索行为定义"
          style="width: 200px"
          @search="handleSearch"
        />
        <a-select
          v-model:value="filterType"
          placeholder="行为类型"
          style="width: 150px"
          @change="handleFilter"
        >
          <a-select-option value="">全部类型</a-select-option>
          <a-select-option
            v-for="type in behaviorTypes"
            :key="type.value"
            :value="type.value"
          >
            {{ type.label }}
          </a-select-option>
        </a-select>
      </a-space>
    </div>

    <!-- 行为定义列表 -->
    <a-table
      :columns="columns"
      :data-source="behaviorDefinitions"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'type'">
          <a-tag :color="getBehaviorTypeColor(record.type)">
            {{ getBehaviorTypeLabel(record.type) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'priority'">
          <a-tag :color="getPriorityColor(record.priority)">
            {{ getPriorityLabel(record.priority) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'enabled'">
          <a-switch
            :checked="record.enabled"
            @change="(checked) => handleToggleEnabled(record.id, checked)"
          />
        </template>

        <template v-else-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="showEditModal(record)">
              编辑
            </a-button>
            <a-button type="link" size="small" @click="showDetailModal(record)">
              详情
            </a-button>
            <a-popconfirm
              title="确定要删除这个行为定义吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 创建/编辑行为定义模态框 -->
    <a-modal
      :open="modalVisible"
      :title="editingBehavior ? '编辑行为定义' : '新建行为定义'"
      width="800px"
      @ok="handleSave"
      @cancel="closeModal"
    >
      <a-form :model="formData" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="行为名称" required>
              <a-input
                v-model:value="formData.name"
                placeholder="请输入行为名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="行为代码" required>
              <a-input
                v-model:value="formData.code"
                placeholder="请输入行为代码"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="行为类型" required>
              <a-select
                v-model:value="formData.type"
                placeholder="请选择行为类型"
              >
                <a-select-option
                  v-for="type in behaviorTypes"
                  :key="type.value"
                  :value="type.value"
                >
                  {{ type.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="优先级" required>
              <a-select
                v-model:value="formData.priority"
                placeholder="请选择优先级"
              >
                <a-select-option value="LOW">低</a-select-option>
                <a-select-option value="NORMAL">普通</a-select-option>
                <a-select-option value="HIGH">高</a-select-option>
                <a-select-option value="URGENT">紧急</a-select-option>
                <a-select-option value="CRITICAL">关键</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="超时时间(秒)">
              <a-input-number
                v-model:value="formData.timeout"
                :min="1"
                :max="3600"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="重试次数">
              <a-input-number
                v-model:value="formData.retryCount"
                :min="0"
                :max="10"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="描述">
          <a-textarea
            v-model:value="formData.description"
            :rows="3"
            placeholder="请输入行为描述"
          />
        </a-form-item>
        <a-form-item label="启用状态">
          <a-switch v-model:checked="formData.enabled" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 行为定义详情模态框 -->
    <a-modal
      :open="detailModalVisible"
      title="行为定义详情"
      width="800px"
      @cancel="closeDetailModal"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="行为名称">{{
          selectedBehavior?.name
        }}</a-descriptions-item>
        <a-descriptions-item label="行为代码">{{
          selectedBehavior?.code
        }}</a-descriptions-item>
        <a-descriptions-item label="行为类型">
          <a-tag :color="getBehaviorTypeColor(selectedBehavior?.type)">
            {{ getBehaviorTypeLabel(selectedBehavior?.type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="优先级">
          <a-tag :color="getPriorityColor(selectedBehavior?.priority)">
            {{ getPriorityLabel(selectedBehavior?.priority) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="超时时间"
          >{{ selectedBehavior?.timeout }}秒</a-descriptions-item
        >
        <a-descriptions-item label="重试次数">{{
          selectedBehavior?.retryCount
        }}</a-descriptions-item>
        <a-descriptions-item label="启用状态">
          <a-tag :color="selectedBehavior?.enabled ? 'success' : 'default'">
            {{ selectedBehavior?.enabled ? '已启用' : '已禁用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">{{
          selectedBehavior?.createdAt
        }}</a-descriptions-item>
        <a-descriptions-item label="描述" :span="2">{{
          selectedBehavior?.description || '-'
        }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import type {
  BehaviorDefinition,
  BehaviorType,
  BehaviorPriority,
} from '#/api/resource-center/behavior-types';
import {
  getBehaviorDefinitions,
  deleteBehaviorDefinition,
  toggleBehaviorDefinition,
} from '#/api/resource-center/behavior-api';
// import BehaviorDefinitionModal from './BehaviorDefinitionModal.vue';
// import BehaviorDefinitionDetailModal from './BehaviorDefinitionDetailModal.vue';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'behavior-created': [behavior: any];
  'behavior-updated': [behavior: any];
  'behavior-enabled': [behaviorId: string];
  'behavior-disabled': [behaviorId: string];
}>();

// 响应式数据
const loading = ref(false);
const behaviorDefinitions = ref<any[]>([]);
const searchKeyword = ref('');
const filterType = ref('');
const modalVisible = ref(false);
const detailModalVisible = ref(false);
const editingBehavior = ref<any>(null);
const selectedBehavior = ref<any>(null);

// 表单数据
const formData = reactive({
  name: '',
  code: '',
  type: '',
  priority: 'NORMAL',
  timeout: 30,
  retryCount: 3,
  description: '',
  enabled: true,
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 行为类型选项
const behaviorTypes = computed(() => [
  { value: 'CREATE', label: '创建' },
  { value: 'UPDATE', label: '更新' },
  { value: 'DELETE', label: '删除' },
  { value: 'START', label: '启动' },
  { value: 'STOP', label: '停止' },
  { value: 'RESTART', label: '重启' },
  { value: 'SCALE', label: '扩缩容' },
  { value: 'MIGRATE', label: '迁移' },
  { value: 'BACKUP', label: '备份' },
  { value: 'RESTORE', label: '恢复' },
  { value: 'DEPLOY', label: '部署' },
  { value: 'ROLLBACK', label: '回滚' },
  { value: 'CONFIGURE', label: '配置' },
  { value: 'MONITOR', label: '监控' },
  { value: 'NOTIFY', label: '通知' },
  { value: 'CUSTOM', label: '自定义' },
]);

// 表格列定义
const columns = [
  {
    title: '行为名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '行为代码',
    dataIndex: 'code',
    key: 'code',
    width: 150,
  },
  {
    title: '行为类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 100,
  },
  {
    title: '超时时间',
    dataIndex: 'timeout',
    key: 'timeout',
    width: 100,
    customRender: ({ text }: { text: number }) => `${text}秒`,
  },
  {
    title: '重试次数',
    dataIndex: 'retryCount',
    key: 'retryCount',
    width: 100,
  },
  {
    title: '启用状态',
    dataIndex: 'enabled',
    key: 'enabled',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 180,
    customRender: ({ text }: { text: string }) =>
      new Date(text).toLocaleString(),
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: '1',
        name: '资源启动',
        code: 'START_RESOURCE',
        type: 'START',
        priority: 'NORMAL',
        timeout: 30,
        retryCount: 3,
        enabled: true,
        createdAt: new Date().toISOString(),
      },
      {
        id: '2',
        name: '资源停止',
        code: 'STOP_RESOURCE',
        type: 'STOP',
        priority: 'HIGH',
        timeout: 15,
        retryCount: 2,
        enabled: true,
        createdAt: new Date().toISOString(),
      },
      {
        id: '3',
        name: '资源备份',
        code: 'BACKUP_RESOURCE',
        type: 'BACKUP',
        priority: 'LOW',
        timeout: 300,
        retryCount: 1,
        enabled: false,
        createdAt: new Date().toISOString(),
      },
    ];

    behaviorDefinitions.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    message.error('加载行为定义失败');
    console.error('加载行为定义失败:', error);
  } finally {
    loading.value = false;
  }
};

const refreshData = () => {
  loadData();
};

const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

const handleFilter = () => {
  pagination.current = 1;
  loadData();
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

const resetFormData = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    type: '',
    priority: 'NORMAL',
    timeout: 30,
    retryCount: 3,
    description: '',
    enabled: true,
  });
};

const showCreateModal = () => {
  editingBehavior.value = null;
  resetFormData();
  modalVisible.value = true;
};

const showEditModal = (behavior: any) => {
  editingBehavior.value = { ...behavior };
  // 将编辑数据填充到表单
  Object.assign(formData, {
    name: behavior.name || '',
    code: behavior.code || '',
    type: behavior.type || '',
    priority: behavior.priority || 'NORMAL',
    timeout: behavior.timeout || 30,
    retryCount: behavior.retryCount || 3,
    description: behavior.description || '',
    enabled: behavior.enabled !== undefined ? behavior.enabled : true,
  });
  modalVisible.value = true;
};

const showDetailModal = (behavior: any) => {
  selectedBehavior.value = behavior;
  detailModalVisible.value = true;
};

const closeModal = () => {
  modalVisible.value = false;
  editingBehavior.value = null;
};

const closeDetailModal = () => {
  detailModalVisible.value = false;
  selectedBehavior.value = null;
};

const handleSave = async () => {
  try {
    const behaviorData = { ...formData };

    if (editingBehavior.value) {
      // 更新
      behaviorData.id = editingBehavior.value.id;
      emit('behavior-updated', behaviorData);
      message.success('更新行为定义成功');
    } else {
      // 创建
      behaviorData.id = Date.now().toString();
      behaviorData.createdAt = new Date().toISOString();
      emit('behavior-created', behaviorData);
      message.success('创建行为定义成功');
    }
    closeModal();
    loadData();
  } catch (error) {
    message.error('保存行为定义失败');
    console.error('保存行为定义失败:', error);
  }
};

const handleDelete = async (id: string) => {
  try {
    message.success('删除成功');
    loadData();
  } catch (error) {
    message.error('删除失败');
    console.error('删除行为定义失败:', error);
  }
};

const handleToggleEnabled = async (id: string, enabled: boolean) => {
  try {
    // 更新本地数据
    const behavior = behaviorDefinitions.value.find((b) => b.id === id);
    if (behavior) {
      behavior.enabled = enabled;
    }

    // 调用API更新状态
    // await toggleBehaviorDefinition(id, enabled);

    message.success(enabled ? '启用成功' : '禁用成功');

    // 触发事件通知父组件
    if (enabled) {
      emit('behavior-enabled', id);
    } else {
      emit('behavior-disabled', id);
    }
  } catch (error) {
    message.error('操作失败');
    console.error('切换行为定义状态失败:', error);

    // 恢复原状态
    const behavior = behaviorDefinitions.value.find((b) => b.id === id);
    if (behavior) {
      behavior.enabled = !enabled;
    }
  }
};

const getBehaviorTypeLabel = (type: string) => {
  const found = behaviorTypes.value.find((t) => t.value === type);
  return found ? found.label : type;foundfound.labelfoundfound.label
};

const getBehaviorTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    CREATE: 'green',
    UPDATE: 'blue',
    DELETE: 'red',
    START: 'green',
    STOP: 'orange',
    RESTART: 'blue',
    SCALE: 'purple',
    MIGRATE: 'cyan',
    BACKUP: 'geekblue',
    RESTORE: 'lime',
    DEPLOY: 'green',
    ROLLBACK: 'red',
    CONFIGURE: 'blue',
    MONITOR: 'purple',
    NOTIFY: 'orange',
    CUSTOM: 'default',
  };
  return colorMap[type] || 'default';
};

const getPriorityLabel = (priority: string) => {
  const labelMap: Record<string, string> = {
    LOW: '低',
    NORMAL: '普通',
    HIGH: '高',
    URGENT: '紧急',
    CRITICAL: '关键',
  };
  return labelMap[priority] || priority;
};

const getPriorityColor = (priority: string) => {
  const colorMap: Record<string, string> = {
    LOW: 'default',
    NORMAL: 'blue',
    HIGH: 'orange',
    URGENT: 'red',
    CRITICAL: 'red',
  };
  return colorMap[priority] || 'default';
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.behavior-definition-panel {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }
}
</style>
